<template>
	<div>
		<div class="search-box">
            <el-select class="mr10" v-model="query.project_id" multiple filterable placeholder="项目编号">
                <el-option
                    v-for="project_id in projectList"
                    :key="project_id"
                    :label="project_id"
                    :value="project_id"
				>
                </el-option> 
            </el-select>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
			<template v-if="props.Edit==='samRec'">
				<el-button type="success" :icon="WarningFilled" @click="handleReceiptCheck">审核通过</el-button>
				<el-button type="danger" :icon="WarningFilled" @click="handleReturnCheck">审核不通过</el-button>
			</template>       
			<slot name="s1"></slot>
		</div>
		<el-table ref="multipleTable" :data="tableSplit()" border header-cell-class-name="table-header"
			@selection-change="handleSelection">
			<el-table-column prop="id" label="ID" width="55" align="center" show-overflow-tooltip></el-table-column>
			<!-- <el-table-column width="90px" prop="receipt_id" label="领用编号" align="center" show-overflow-tooltip></el-table-column> -->
			<el-table-column prop="project_id" label="项目编号" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column width="120px" sortable prop="sample_id" label="样品编号" align="center" show-overflow-tooltip></el-table-column>
			<!-- <el-table-column prop="sample_name" label="样品名称" align="center" show-overflow-tooltip></el-table-column> -->
			<!-- <el-table-column prop="lot_number" label="批号" align="center" show-overflow-tooltip></el-table-column> -->
			<template v-if="props.Edit==='samRec'">
				<el-table-column width="100px" prop="current_amount" label="原始库存量" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column width="100px" prop="disp_amount" label="分装总库存" align="center" show-overflow-tooltip></el-table-column>
			</template>
			<el-table-column sortable width="100px" prop="receipt_amount" label="领用量" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="return_amount" label="退回量" align="center" show-overflow-tooltip></el-table-column>
			<!-- <el-table-column prop="create_time" label="有效日期" align="center" show-overflow-tooltip></el-table-column> -->
			<!-- <el-table-column prop="status" label="样品状态" align="center" show-overflow-tooltip>
				<template #default="scope">
					<el-tag v-if="scope.row.status===0" type="info">未审核</el-tag>
					<el-tag v-if="scope.row.status===1" type="warning">暂存</el-tag>
					<el-tag v-if="scope.row.status===2" type="primary">待检</el-tag>
					<el-tag v-if="scope.row.status===3" type="success">在检</el-tag>
					<el-tag v-if="scope.row.status===4" type="danger">检闭</el-tag>
					<el-tag v-if="scope.row.status===5" type="danger">销毁</el-tag>
					<el-tag v-if="scope.row.status===6" type="warning">返回</el-tag>
				</template>
			</el-table-column> -->
			<el-table-column sortable width="120px" prop="dflag" label="领用分装样品" align="center" show-overflow-tooltip>
				<template #default="scope">
					<el-tag v-if="scope.row.dflag===1" type="success">是</el-tag>
					<el-tag v-if="scope.row.dflag===0" type="warning">否</el-tag>
				</template>
			</el-table-column>
			<el-table-column sortable width="90px" prop="rflag" label="分装退回" align="center" show-overflow-tooltip>
				<template #default="scope">
					<el-tag v-if="scope.row.rflag===-1" type="info">待定</el-tag>
					<el-tag v-if="scope.row.rflag===1" type="success">是</el-tag>
					<el-tag v-if="scope.row.rflag===0" type="warning">否</el-tag>
				</template>
			</el-table-column>
			<el-table-column sortable width="110px" prop="rec_stat" label="领用状态" align="center" show-overflow-tooltip>
				<template #default="scope">
					<el-tag v-if="scope.row.rec_stat===0" type="info">领用审核中</el-tag>
					<el-tag v-if="scope.row.rec_stat===1" type="success">领用通过</el-tag>
					<el-tag v-if="scope.row.rec_stat===2" type="warning">领用不通过</el-tag>
					<el-tag v-if="scope.row.rec_stat===3" type="warning">退回审核中</el-tag>
					<el-tag v-if="scope.row.rec_stat===4" type="primary">退回通过</el-tag>
					<el-tag v-if="scope.row.rec_stat===5" type="danger">退回不通过</el-tag>
				</template>
			</el-table-column>
			<el-table-column sortable prop="create_time" label="创建日期" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column sortable prop="applicant" label="领用人" align="center" show-overflow-tooltip></el-table-column>
			<template v-if="props.Edit==='samRec'">
				<el-table-column label="操作" align="center" width="170px">
					<template #default="scope">
						<el-button
							type="primary"
							size="small"
							:icon="View"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							查看
						</el-button>
						<el-button
							type="success"
							size="small"
							:icon="Edit"
							@click="handleEdit(scope.$index,scope.row,'样品领退|编辑')"
							v-permiss="15"
						>
							编辑
						</el-button>
					</template>
        		</el-table-column>
			</template>
			<el-table-column type="selection"></el-table-column>
		</el-table>
		<div class="pagination">
			<el-pagination
				background
				layout=" prev, pager, next,jumper,total"
				:current-page="state.pageIndex"
				:page-size="state.pageSize"
				:total="pageTotal"
				@current-change="handlePageChange"
			></el-pagination>
		</div>
		<el-dialog 
			draggable 
			title="样品详情" 
			v-model="viewVisible" 
			destroy-on-close
			:close-on-click-modal="false"
		>
			<sampleDetail :data="rowData" :Type="Type" />
		</el-dialog>
		<el-dialog 
			draggable 
			title="样品编辑" 
			v-model="editVisible" 
			destroy-on-close
			:close-on-click-modal="false"
		>
			<receiptAndreturnEdit ref="returnEdit" 
				:data="rowData" :update="update" :edit="idEdit" :actionType="actionType">
			</receiptAndreturnEdit>
		</el-dialog>
		<slot name="s2" :multiple_selection="multiple_selection" ></slot>
	</div>
</template>

<script setup lang="ts">
import { pa } from 'element-plus/es/locale'
import { ref,reactive, onMounted,onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import sampleReturn from '../sample_return.vue'
import { Delete, InfoFilled, WarningFilled,Search,Edit, Sort, CirclePlusFilled, View,RemoveFilled } from '@element-plus/icons-vue'
import useReceipt from '../../../hooks/Receipt/useReceipt'
import { postData } from '../../../api/index'
import useUtils from '../../../hooks/useUtils'
import sampleDetail from './sample_detail.vue'
import receiptAndreturnEdit from './receiptAndreturnEdit.vue'

const { arrRemoveDup } = useUtils()
const { getReceipt,postReceiptAction } = useReceipt()
const projectList = ref([])
const reload = () => {
	getReceipt().then(
		res=>{
			tableData.value=res.data
			for(let item of res.data){
				projectList.value.push(item.project_id)
			} 
			projectList.value=arrRemoveDup(projectList.value)
		}
	)
}

defineExpose({
	reload,
})
/* 接收父组件值 */
const props = defineProps({
	tableData: {
		type:Object,
		required: false
	},
	Edit: {
		type: String,
		required: false
	}
})

interface TableItem { 
	id: number;
	receipt_id: string;
	project_id: string;
	client_id: string;
	sample_id: string;
	sample_name: string;
	lot_number: string;
	size: string;
	sample_amount: number;
	current_amount: number;
	return_amount: number;
	arrive_time: string;
	instock_time: string;
	create_time: string;
	status:number;
	rec_stat:number;
	dflag: number;
	rflag: number;
	applicant: string;
}
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
const state = reactive({
	page:1,
	limit:20,
	pageIndex:1,
	pageSize:20,
	total:pageTotal
})

const tableSplit = () => {
   if(props.Edit==="samRec"){
	   	let table = ref(tableData.value.filter(
			(item,index) => {
				return item.status === 3 && 
				(item.rec_stat === 0 || item.rec_stat === 3 ) 
			})
		)
		pageTotal.value=table.value.length
		return(table.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1) 
			}
		))
	}
	if(props.Edit==="recMan"){
		let table = ref(tableData.value.filter(
			(item,index) => {
				return item.status === 3
			})
		)
		pageTotal.value=table.value.length
		return(table.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1) 
			}
		))
	}
}
const handlePageChange = (val: number) => {
	state.pageIndex = val;
	state.page = val;
};
/* 记录多选选项 */
let multiple_selection = reactive([])
const handleSelection = (val:any) => {
	if(val.length === 0){
	} else {
		multiple_selection = val
	}
}
/* 设置查看参数 */
const viewVisible = ref(false)
const rowData = ref({})
const Type = ref("")
/* 查看样品信息 */
const handleView = (row: TableItem) => {
	viewVisible.value=true;
	rowData.value = row;
	Type.value="samRec"
}
/* 编辑信息 */
const index=ref(-1)
const editVisible = ref(false)
const idEdit = ref(false)
const actionType = ref("")
const handleEdit = (idx:number,row:TableItem,tag:string) => {
	editVisible.value=true;
	idEdit.value=true;
	index.value=idx;
	rowData.value=row;
	actionType.value=tag 
}
/* 样品领用数据 */
interface ReceiptData {
	totalReceiptAmount: number;
	currentAmount: number;
	sample_id: string;
	receipt_id: string;
}
// const receiptData:ReceiptData = {}
const handleReceiptCheck = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定审核通过吗？', '提示',{
			type:"success",
			draggable: true,
		})
		.then( res => {
			const receipt_samples = ref({})
			const return_samples = ref({})
			const checked_sample = ref(0)
			multiple_selection.forEach(
				item => {
					if(item.rec_stat !==0 && item.rec_stat !==3 ){
						checked_sample.value=checked_sample.value + 1
					}else{
						if(item.rec_stat === 0){
							if(!receipt_samples.value[item.sample_id]){
								receipt_samples.value[item.sample_id] = []
							}
							receipt_samples.value[item.sample_id].push(item)
						}else if(item.rec_stat === 3){
							if(!return_samples.value[item.sample_id]){
								return_samples.value[item.sample_id] = []
							}
							return_samples.value[item.sample_id].push(item)
						}
					}
				}
			)
			if(checked_sample.value > 0){
				ElMessage.error("请剔除已审核的样品，已经审核的样品无法重复审核！！")
			}else{
				if(Object.keys(receipt_samples.value).length !==0){
					postReceiptAction(receipt_samples.value,"receive").then( res => {
						if(res.data === 202){
							reload()
							ElMessage.success("审核通过！")
						}else if(res.data === 203){
							ElMessage.error("样品量超出库存，请重新审核！！")
						}
					})
					// for (const [samID,value] of Object.entries(receipt_samples.value)){
					// 	const totalReceiptAmount=ref(0)
					// 	const currentAmount=ref(0)
					// 	for(let item of value){
					// 		totalReceiptAmount.value = totalReceiptAmount.value + item.receipt_amount
					// 		currentAmount.value = item.current_amount
					// 	}
					// 	if(totalReceiptAmount.value > currentAmount.value){
					// 		ElMessage.error(
					// 			"样品编号 "
					// 			+ samID 
					// 			+ "（审核通过量=>" 
					// 			+ String(totalReceiptAmount.value) 
					// 			+ "大于库存量=>" 
					// 			+ String( currentAmount.value) 
					// 			+ "）请核对领用单后重新审核!"
					// 		)
					// 	}else{
					// 		reload()
					// 	}
					// }
				}
				if(Object.keys(return_samples.value).length !==0){
					postReceiptAction(return_samples.value,"return").then( res => {
						if(res.data === 202){
							reload()
							ElMessage.success("审核通过！")
						}else{
							ElMessage.error("审核出错，请重新审核！！")
						}
					})
				}	
			}
		}).catch(err => {console.log(err)});
	}
}
const handleReturnCheck = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定审核不通过吗？', '提示',{
			type:"warning",
			draggable: true,
		})
		.then( res => {
			const receipt_samples = ref([])
			const return_samples = ref([])
			multiple_selection.forEach(
				item => {
					if(item.rec_stat === 0){
						receipt_samples.value.push(item)
					}else if(item.rec_stat === 3){
						return_samples.value.push(item)
					}
				}
			)
			if(Object.keys(receipt_samples.value).length !==0){
				for (const [samID,value] of Object.entries(receipt_samples.value)){
					postReceiptAction(value,"receipt_fail")
					for(var idx=0;idx<tableData.value.length;idx++){
						if(tableData.value[idx].receipt_id===value.receipt_id){
							tableData.value[idx].rec_stat=2
						}
					}
				}
			}
			if(Object.keys(return_samples.value).length !==0){
				for (const [samID,value] of Object.entries(return_samples.value)){
					postReceiptAction(value,"return_fail")
					for(var idx=0;idx<tableData.value.length;idx++){
						if(tableData.value[idx].receipt_id===value.receipt_id){
							tableData.value[idx].rec_stat=5
						}
					}
            	}
			}
		}).catch(() => {});
	}
}
/* 项目检索 */
const query = reactive({
	project_id: "",
	limit: 2,
	pageIndex: 1,
	pageSize: 1
});
/* 检索方法 */
const { queryReceiptProject } = useReceipt()
const handleSearch = () => {
	if(query.project_id.length === 0){
		ElMessage({
			type: 'error',
			message: `请选中至少一个项目！`,
		})
	}else{
		queryReceiptProject(query).then( res => {
			tableData.value=res.data
		})
	}
}
/* 更新方法 */
const update = () => {
	reload();
	editVisible.value=false;
}
</script>

<style scoped>
.search-box {
	margin-bottom: 20px;
	float:left
}

.mr10 {
	margin-right: 10px;
} 
.el-select {
	width: 800px;
}

.search {
	float:right;
	margin-bottom: 20px;
}

.search-input {
	width: 200px;
}


.el-link {
  margin-left: 8px;
}

.mr10 {
	margin-right: 10px;
}

.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}
.upload-demo {
    width: 360px;
}
</style>
